package i18nit

import grails.validation.ValidationException
import org.springframework.context.MessageSource

import static org.springframework.http.HttpStatus.*

class CompanyController {
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    MessageSource messageSource

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Company.list(params), model: [companyCount: Company.count()]
    }

    def show(Long id) {
        respond Company.get(id)
    }

    def save(Company company) {
        if (company == null) {
            render status: NOT_FOUND
            return
        }
        println "[controller]" + request.locale
        company.save(flush: true)

        if (company.hasErrors()) {
            company.errors.allErrors.each {
                println "[controller]" + messageSource.getMessage(it, request.locale)
            }
            respond company.errors, view: 'create'
            return
        }

        respond company, [status: CREATED, view: "show"]
    }

    def update(Company company) {
        if (company == null) {
            render status: NOT_FOUND
            return
        }

        try {
            company.save(flush: true)
        } catch (ValidationException e) {
            respond company.errors, view: 'edit'
            return
        }

        respond company, [status: OK, view: "show"]
    }

    def delete(Long id) {
        if (id == null) {
            render status: NOT_FOUND
            return
        }

        Company.get(id).delete(flush: true)

        render status: NO_CONTENT
    }
}
